package com.ilongsay.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Author ilongsay
 * @Email ilongsay@163.com
 * @Copyright 版本所有，侵权必究！
 * @Description 注意：这里是版本1.0 继承这个AbstractSessionDAO会出现发现doReadSession方法调用过于频繁
 * 舍弃不用，准备用新的版本
 * @Create 2018-08-14 13:55
 */
@Component
public class MyCachingSessionDao extends AbstractSessionDAO{

	@Autowired
	private RedisSessionDao redisSessionManager;

	/**
	 *@author ilongsay
	 *@Createtime 2018-08-14 14:12
	 *@Description 创造一个session
	  * @param session 传入的session
	 *@return java.io.Serializable
	 */
	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		//添加到redis中
		redisSessionManager.hadd(sessionId.toString(),session);
		return sessionId;
	}

	/**
	 *@author ilongsay
	 *@Createtime 2018-08-14 14:31
	 *@Description 取出相关的session
	  * @param sessionId
	 *@return org.apache.shiro.session.Session
	 */
	@Override
	protected Session doReadSession(Serializable sessionId) {
		return  redisSessionManager.hget(sessionId.toString());
	}

	/**
	 *@author ilongsay
	 *@Createtime 2018-08-14 14:32
	 *@Description 更新session
	  * @param session
	 *@return void
	 */
	@Override
	public void update(Session session) throws UnknownSessionException {
		if (session == null || session.getId() == null) {
			System.out.println("Session is null");
			return;
		}
		Serializable sessionId = session.getId();
		redisSessionManager.hadd(sessionId.toString(),session);
	}

	@Override
	public void delete(Session session) {
		if(session == null || session.getId() == null){
			System.out.println("Session is null");
			return;
		}
		redisSessionManager.hdelete(session.getId().toString());
	}

	@Override
	public Collection<Session> getActiveSessions() {
		List<Session> list = redisSessionManager.hmget();
		return list;
	}
}
